<template>
  <div>
    <!-- 添加或修改配置参数对话`框 -->
    <el-dialog
      v-model="visible"
      :title="title"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        v-loading="loading"
        ref="editForm"
        :model="listForms"
        :rules="rules"
        label-width="135px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickName">
              <el-input
                v-model="listForms.nickName"
                placeholder="请输入用户姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-cascader
                ref="cascaderRef"
                v-model="listForms.deptId"
                :options="deptOptions"
                :props="props1"
                clearable
                placeholder="请选择归属部门"
                :show-all-levels="false"
              />
              <!-- <el-tree-select
                v-model="listForms.deptId"
                :data="deptOptions"
                node-key="id"
                multiple
              /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input
                v-model="listForms.phoneNumber"
                placeholder="请输入手机号"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="listForms.email"
                placeholder="请输入邮箱"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="listForms.userId == undefined" :span="12">
            <el-form-item
              label="用户账号"
              prop="userName"
            >
              <el-input
                v-model="listForms.userName"
                placeholder="请输入用户账号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="sex">
              <el-select
                v-model="listForms.sex"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in dicts[DictDirection.用户性别]"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="listForms.status">
                <el-radio
                  v-for="dict in dicts[DictDirection.是否禁用字典]"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >
                  {{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职级" prop="postId">
              <el-select
                v-model="listForms.postId"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="roleIds">
              <el-select
                v-model="listForms.roleIds"
                filterable
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="listForms.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
            <el-divider></el-divider>
          </el-col>
        </el-row>
        <el-collapse v-model="basicInfos" @change="basicInfoChange">
          <el-collapse-item name="basicInfo" title="基础信息">
            <el-col :span="12">
              <el-form-item label="入职时间" prop="entryTime">
                <el-date-picker
                  v-model="basicForms.entryTime"
                  clearable
                  type="date"
                  placeholder="请选择入职时间"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </el-form-item>
            </el-col>
              
            <el-col :span="12">
              <el-form-item label="转正时间" prop="turnPositiveTime">
                <el-date-picker
                  v-model="basicForms.turnPositiveTime"
                  clearable
                  type="date"
                  placeholder="请选择转正时间"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="岗位晋升任命时间" prop="jobPromotionTime">
                <el-date-picker
                  v-model="basicForms.jobPromotionTime"
                  clearable
                  type="date"
                  placeholder="请选择岗位晋升任命时间"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="dateOfBirth">
                <el-date-picker
                  v-model="basicForms.dateOfBirth"
                  clearable
                  type="date"
                  placeholder="请选择出生日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="员工编号" prop="employeeId">
                <el-input
                  v-model="basicForms.employeeId"
                  clearable
                  placeholder="请输入员工编号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="试用期薪资" prop="probationPeriodSalary">
                <el-input
                  v-model="basicForms.probationPeriodSalary"
                  clearable
                  placeholder="请输入试用期薪资"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="转正薪资" prop="positiveSalary">
                <el-input
                  v-model="basicForms.positiveSalary"
                  clearable
                  placeholder="请输入转正薪资"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号码" prop="idNumber">
                <el-input
                  v-model="basicForms.idNumber"
                  clearable
                  placeholder="请输入身份证号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input
                  v-model="basicForms.age"
                  clearable
                  placeholder="请输入年龄"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="户籍地" prop="domicile">
                <el-input
                  v-model="basicForms.domicile"
                  clearable
                  placeholder="请输入户籍地"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系地址" prop="address">
                <el-input
                  v-model="basicForms.address"
                  clearable
                  placeholder="请输入联系地址"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input
                  v-model="basicForms.emergencyContact"
                  clearable
                  placeholder="请输入紧急联系人"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人电话" prop="telephone">
                <el-input
                  v-model.trim="basicForms.telephone"
                  clearable
                  placeholder="请输入紧急联系人电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学历" prop="education">
                <el-input
                  v-model="basicForms.education"
                  clearable
                  placeholder="请输入学历"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="毕业院校" prop="graduatedSchool">
                <el-input
                  v-model="basicForms.graduatedSchool"
                  clearable
                  placeholder="请输入毕业院校"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业" prop="profession">
                <el-input
                  v-model="basicForms.profession"
                  clearable
                  placeholder="请输入专业"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户行" prop="accountBank">
                <el-input
                  v-model="basicForms.accountBank"
                  clearable
                  placeholder="请输入开户行"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="卡号" prop="cardNumber">
                <el-input
                  v-model="basicForms.cardNumber"
                  clearable
                  placeholder="请输入银行卡卡号"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, defineExpose, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { ElTree } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { getUser, addUser, updateUser, treeselect, userDeptTreeselect } from '@/api/system/user'
import userStore from '@/store/modules/user'
import type {  FormRules } from 'element-plus'


const store = userStore()
const userInfo = computed(() => store.user)
const userInfoList = JSON.parse(JSON.stringify(userInfo.value))
const dicts = useDicts()
dicts.setDicts(DictDirection.用户性别)

const visible = ref<boolean>(false)
const title = ref<string>('')

const props = defineProps<{
  deptOptions,
}>()

// 部门列表
const listForms = ref({
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  password: undefined,
  phoneNumber: undefined,
  email: undefined,
  sex: undefined,   
  status: 0,
  remark: undefined,
  postId: undefined,
  roleIds: [],
})
const basicForms = ref({
    entryTime: '',
    turnPositiveTime: undefined,
    jobPromotionTime: undefined,
    dateOfBirth: undefined,
    jobNumber: undefined,
    probationPeriodSalary: undefined,
    positiveSalary: undefined,
    idNumber: undefined,
    emergencyContact: undefined,
    address: undefined,
    telephone: undefined,
    education: undefined,
    graduatedSchool: undefined,
    profession: undefined,
    employeeId: undefined,
    accountBank: undefined,
    cardNumber: undefined,
    domicile: undefined,
    age: undefined,
  }),
  // 基础数据
  basicInfos = ref(undefined),
  // 表单验证
  rules:FormRules = {
    userName: [
      { required: true, message: '用户账号不能为空', trigger: 'blur' },
    ],
    nickName: [
      { required: true, message: '用户姓名不能为空', trigger: 'blur' },
    ],
    deptId: [{ required: true, message: '归属部门不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
    ],
    email: [
      { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
      {
        type: 'email',
        message: '\'请输入正确的邮箱地址',
        trigger: ['blur', 'change'],
      },
    ],
    phoneNumber: [
      { required: true, message: '手机号码不能为空', trigger: 'blur' },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      },
    ],
    postId: [
      { required: true, message: '职级不能为空', trigger: 'blur' },
    ],
    status: [
      { required: true, message: '状态不能为空', trigger: 'blur' },
    ],
  },
  cascaderRef = ref(null)

const props1 = {
    checkStrictly: true,
    multiple: false, // 删除多选
    emitPath: false, // 只返回该节点的值
    label: 'label',
    value: 'id',
  },
  // 新增修改表单
  editForm = ref(null),
  {
    proxy,
  }:{
    proxy:any
  } = getCurrentInstance()

// 获取部门权限
const deptOptions = ref([])
const getdeptTreeselect = () => {
  treeselect().then((res) => {
    deptOptions.value = res.data
  })
}
getdeptTreeselect()
// 分配部门权限
const getUserDeptTreeselect = (id) => userDeptTreeselect(id).then(res => {
  deptOptions.value = res.data.dept
  return res
})
// 获取角色列表和岗位
const postOptions = ref([])
const roleOptions = ref([])
const deptRef = ref<InstanceType<typeof ElTree>>()
const getUserDetail = () => {
  return getUser(1).then((res) => {
    postOptions.value = res.data.posts 
    roleOptions.value = res.data.roles
  })
}

const emit = defineEmits(['changeList'])

// 重置新增修改用户信息列表
const reset = () => {
  listForms.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phoneNumber: undefined,
    email: undefined,
    sex: undefined,
    status: 0,
    remark: undefined,
    postId: undefined,
    roleIds: [],
  }
  basicForms.value = {
    entryTime: '',
    turnPositiveTime: undefined,
    jobPromotionTime: undefined,
    dateOfBirth: undefined,
    jobNumber: undefined,
    probationPeriodSalary: undefined,
    positiveSalary: undefined,
    idNumber: undefined,
    emergencyContact: undefined,
    address: undefined,
    telephone: undefined,
    education: undefined,
    graduatedSchool: undefined,
    profession: undefined,
    employeeId: undefined,
    accountBank: undefined,
    cardNumber: undefined,
    domicile: undefined,
    age: undefined,
  }
  proxy.$resetForm(editForm.value)
}

// 基础信息tab切换
const basicInfoChange = () => {
  basicInfos.value = 'basicInfo'
}
// 新增修改用户信息——确定
const submitForm = () => {
  proxy.$validateForm(editForm.value, () => {
    let msg = ''
    let response = null
    let sysUserDetailDto = null
    let userClassify = null // 用户分类
    let userType = null // 用户类型
    userClassify = userInfoList.userClassify
    userType = userInfoList.userType
    sysUserDetailDto = basicForms.value ? basicForms.value : {}
    const data = {
      sysUserDetailDto,
      ...listForms.value,
      userClassify,
      userType,
    }
    if (listForms.value.userId != undefined) {
      msg = '修改成功'
      response = updateUser(data)
    } else {
      msg = '新增成功'
      response = addUser(data)
    }
    response
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(msg)
        cancel()
        emit('changeList')
      } else {
        ElMessage.error(res.msg)
      }
    })
    .catch((error) => {
      if (error == 'cancel') {
        ElMessage.error(error)
      }
    })
  })
}
// 修改新增用户信息——取消
const cancel = () => {
  reset()
  visible.value = false
}
const form = ref(null),
  basis = ref(null)
const getList = (id) => {
 return getUser(id).then((res) => {
    console.log(res)
    
    form.value = res.data.data
    basis.value = res.data.details ? res.data.details : {}
    listForms.value = { ...form.value }
    basicForms.value = { ...basis.value }
    postOptions.value = res.data.posts   
    roleOptions.value = res.data.roles
    // listForms.value.postId = res.data.data.postId
    // listForms.value.roleIds = res.data.data.roleId
    listForms.value.password = ''
  })
}

dicts.setDicts(DictDirection.是否禁用字典)


const loading = ref<boolean>(false)
const open = async (t, id) => {
    visible.value = true
    title.value = t
    
    loading.value = true
    if(id){
      await getList(id)
    }else{
      await getUserDetail()
    }
    loading.value = false
}


defineExpose({
  listForms,
  getUserDeptTreeselect,
  deptRef,
  open
})
</script>
<style lang="less" scoped>
.information {
  line-height: 24px;
  font-size: 16px;
  color: #303133;
}
.tree_border {
  border: 0 solid #ccc;
  border-radius: 5px;
}
/deep/.el-form-item__content {
  display: inline-block;
}
</style>
